﻿using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Hxsoft.AppV1.Module;

namespace Hxsoft.AppV1._Controls
{
	[ValidationProperty("SelectedValue")]
	public partial class SiteSelector : System.Web.UI.UserControl
	{
		public event EventHandler SelectedIndexChanged;

		public bool Enabled
		{
			get { return CtrSelector.Enabled; }
			set { CtrSelector.Enabled = value; }
		}

		private LoadedValue<int[]> loadedSiteIds;
		public int[] SiteIds
		{
			get
			{
				if (loadedSiteIds.Loader == null)
					loadedSiteIds.Loader = () => (int[])ViewState["SiteIds"];
				return loadedSiteIds.Value;
			}
			set
			{
				if (loadedSiteIds.Setter == null)
					loadedSiteIds.Setter = v => ViewState["SiteIds"] = v;
				loadedSiteIds.Value = value;
			}
		}


		public string SelectedValue
		{
			get { return CtrSelector.SelectedValue; }
			set
			{
				CtrSelector.DataBind();
				if (CtrSelector.Items.FindByValue(value) != null)
					CtrSelector.SelectedValue = value;
			}
		}

		public bool AutoPostBack
		{
			get { return CtrSelector.AutoPostBack; }
			set { CtrSelector.AutoPostBack = value; }
		}


		private bool isBindCtrSelector = false;
		protected void CtrSelector_DataBinding(object sender, EventArgs e)
		{
			if (isBindCtrSelector) return;
			if (SiteIds != null)
				CtrSelector.DataSource = Sites.GetItems(SiteIds);
			else
				CtrSelector.DataSource = Sites.GetItems();
			CtrSelector.DataTextField = "SiteName";
			CtrSelector.DataValueField = "SiteId";
		}

		protected void CtrSelector_DataBound(object sender, EventArgs e)
		{
			CtrSelector.EnsurePrompt();

			CtrSelector.DataSource = null;
			isBindCtrSelector = true;
		}

		protected virtual void OnSelectedIndexChanged(EventArgs e)
		{
			if (SelectedIndexChanged != null)
				SelectedIndexChanged(this, e);
		}

		protected void CtrSelector_SelectedIndexChanged(object sender, EventArgs e)
		{
			OnSelectedIndexChanged(e);
		}
	}
}